package cau.se.project;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;

import cau.se.project.data.CLSXTreeModel;
import cau.se.project.data.method.RowControl;
import cau.se.project.method.CLSXControl;
import cau.se.project.method.FileControl;

public class DSMFile implements FileControl {

	private File currentFile = null;	// 현재 열려있는 파일

	public DSMFile()
	{
		newFile();
	}

	@Override
	public void newFile() {
		System.out.println("new DSMFILE");
		currentFile = null;
	}

	@Override
	public CLSXControl open(File file) throws Exception {
		newFile();

		System.out.println("open dsmFile " + file.getAbsolutePath());
		
		CLSXControl clsx = new CLSXTreeModel();
		BufferedReader br = new BufferedReader(new FileReader(file));
		String line;

		// 첫번째 줄: 행 개수 
		int numRow = Integer.parseInt(br.readLine());

		// 그다음: dependency 정보
		// 일시저장용 matrix 행렬
		int[][] matrix = new int[numRow][];
		for(int i=0; i<numRow; i++) {
			matrix[i] = new int[numRow];
			line = br.readLine();
			String[] e = line.split(" ");
			for(int j=0; j<numRow; j++) {
				if(e[j].equals("1")) {
					matrix[i][j] = 1;
				}
				else {
					matrix[i][j] = 0;
				}
			}
		}

		// 이름으로 row를 생성
		List<RowControl> tempList = new ArrayList<>();
		for(int i=0; i<numRow; i++) {
			line = br.readLine();
			RowControl rc = clsx.makeRow(line);
			clsx.addRow(rc);
			tempList.add(rc);
		}

		// 생성된 row에 dependency 정보 적용
		for(int i=0; i<numRow; i++) {
			for(int j=0; j<numRow; j++) {
				if(matrix[i][j] == 1) {
					tempList.get(i).setDependency(tempList.get(j));
				}
			}
		}

		br.close();
		System.out.println("elements: " + clsx.getDSM().getSize());

		// currentFile 갱신
		currentFile = file;
		return clsx;
	}

	@Override
	public void save(CLSXControl clsx) throws Exception
	{
		System.out.println("save to " + currentFile.getAbsolutePath());
		int[][] matrix = clsx.getArray();
		String[] nameList = clsx.getNameList();

		BufferedWriter writer = new BufferedWriter(new FileWriter(this.currentFile));

		writer.write("" + matrix.length);
		writer.write("\n");

		int size = matrix.length;
		for ( int i = 0; i < size; i++ ) {
			for ( int j = 0; j < size; j++ ) {
				writer.write(matrix[i][j] + " ");
			}
			writer.write("\n");
		}
		for ( int i = 0; i < size; i++ ) {
			writer.write(nameList[i]);
			writer.write("\n");
		}

		writer.close();
	}

	@Override
	public void saveAs(CLSXControl clsx, File file) throws Exception
	{
		this.currentFile = file;
		save(clsx);
	}

	@Override
	public File getCurrentFile() {
		return currentFile;
	}
}
